package javango.forms.fields;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

import javango.forms.widgets.TextInputWidget;
import javango.forms.widgets.WidgetFactory;

public class EmailField extends AbstractField<String> {
	public final static String EMAILREGEXP = "[A-Z0-9._%-][+A-Z0-9._%-]*@(?:[A-Z0-9-]+\\.)+[A-Z]{2,4}$";
	
	@Inject
	public EmailField(WidgetFactory widgetFactory) {
		super(widgetFactory);
		this.setWidget(TextInputWidget.class);
	}

	@Override
	public String clean(String value, Map<String, String> errors) {
		if (StringUtils.isEmpty(value)) {
			if (isRequired()) { 
				errors.put(getName(), REQUIRED_ERROR);
				return null;
			} else if (isAllowNull()) {
				return null;
			}
			return "";
		} 
		if (!value.toUpperCase().matches(EMAILREGEXP)) {
			errors.put(this.getName(), "Enter a valid e-mail address.");
		}
		return value;		
	}
	
}
